package listener;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.annotation.Resource;
import javax.sql.DataSource;

import model.MenuRepository;
import myBeans.MenuInfo;
import myBeans.UserInfo;

/**
 * Application Lifecycle Listener implementation class Init
 *
 */
@WebListener
public class Init implements ServletContextListener {

    /**
     * Default constructor. 
     */
    public Init() {
        // TODO Auto-generated constructor stub
    }
    
    @Resource(name = "jdbc/sharewithme")
	private DataSource jdbcShareWithMe;
	
	private Connection conn;

	/**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
    	try{
    		conn = jdbcShareWithMe.getConnection();
    		
    		arg0.getServletContext().setAttribute("connection", conn);
    		
    		//SET default menu
    		
    		List<MenuInfo> defaultMenu = new MenuRepository(conn).GetMenuDefault();
    		UserInfo defaultUser = new UserInfo();
    		
    		defaultUser.setMenus(defaultMenu);
    		arg0.getServletContext().setAttribute("DefaultUser", defaultUser);

    	}
    	catch(SQLException ex){
    		ex.printStackTrace();
    	}
    }

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
    	try{
    		conn.close();
    		//arg0.getServletContext().removeAttribute("DBConnection");
    	}
    	catch(SQLException ex){
    		ex.printStackTrace();
    	}
    }
	
}
